package com.have.blog.picture.service.impl;

import com.have.blog.model.models.TFileSort;
import com.have.blog.picture.service.LocalFileService;
import com.have.blog.utils.DateUtils;
import com.have.blog.utils.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class LocalFileServiceImpl implements LocalFileService {

    /**
     * 本地图片上传路径
     */
    @Value(value = "${file.upload.path}")
    private String FILE_UPLOAD_PATH;

    @Override
    public String uploadFile(MultipartFile filedata, TFileSort fileSort, String fileName) throws IOException {
        return uploadSingleFile(filedata, fileSort, fileName);
    }

    private String uploadSingleFile(MultipartFile multipartFile, TFileSort fileSort, String fileName) throws IOException {
        String sortUrl = fileSort.getUrl();
        if (StringUtils.isEmpty(sortUrl)) {
            sortUrl = "base/common/";
        }
        String oldName = multipartFile.getOriginalFilename();
        String picExpandedName = FileUtils.getPicExpandedName(oldName);

        String filePath = FILE_UPLOAD_PATH + sortUrl  + "/" +  picExpandedName + "/" + DateUtils.getYears() + "/"
                + DateUtils.getMonth() + "/" + DateUtils.getDay() + "/";
        String picUrl = sortUrl + "/" + picExpandedName + "/" + DateUtils.getYears() + "/"
                + DateUtils.getMonth() + "/" + DateUtils.getDay() +"/" + fileName;
        String saveUrl = filePath + fileName;

        // 保存本地创建目录
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        File saveFile = new File(saveUrl);
        saveFile.createNewFile();
        multipartFile.transferTo(saveFile);
        return picUrl;
    }
}
